/**
 * Created by xiaoz on 16/8/13.
 */
define(["utils","base"],function(utils,baseClass){
    var Component = function(config){
        var _this = this;
        Component.baseConstructor.call(this,config);
        this.$el.addClass("yy-timepicker");
        this.input = $("<input readonly='readonly' type='text'/>");
        this.$el.append(this.input);
        this.dropdown = null;
        this.minSpan = config.minSpan || 1;
        this.mode = config.mode ||"";
        this.minInfo = {hour:-1,min:-1};
        this.mode = this.mode.toUpperCase();
        if(this.mode==="AM"){
          this.hourRange = [0,12];
        }else if(this.mode=="PM"){
          this.hourRange = [12,23];
        }else{
          this.hourRange = [0,23];
        }
        this.input.bind("click",function(e){
          e.stopPropagation();
          e.preventDefault();
          _this.pageview.pageManager.triggerBodyClickWithoutSelf(_this);
          _this.show(e)
        });
        this.value = config.value;
        this._init();

        this.curKeyDown = "hour";
        this.input.bind("keydown",function(e){
          if(e.keyCode===40){
            //下
            e.stopPropagation();
            e.preventDefault();
            _this._selectDown();
          }else if(e.keyCode===38){
            e.stopPropagation();
            e.preventDefault();
            _this._selectUp();
            //上
          }else if(e.keyCode===37){
            e.stopPropagation();
            e.preventDefault();
            //左
            _this.curKeyDown = "hour";
          }else if(e.keyCode===39){
            e.stopPropagation();
            e.preventDefault();
            _this.curKeyDown = "min";
            //右
          }else if(e.keyCode===13||e.keyCode===9){
            e.stopPropagation();
            e.preventDefault();
            _this.hide();
          }
        });

        var changeMethodName = config.comKey+"_change";
        this.changeMethod = this.pageview.plugin[changeMethodName];

    }

    utils.extendClass(Component,baseClass);

    Component.prototype._selectDown = function(){

      if(this.curKeyDown === "hour"){
        var nextHour = this.hour+1;
        if(nextHour<=this.hourRange[1]){
          this.hour = nextHour;
          this.setValue(this.getValueStr());
          this.setHourPos();
        }
      }else{
        var nextMin = this.min+this.minSpan;
        if(nextMin<=59){
          this.min = nextMin;
          this.setValue(this.getValueStr());
          this.setMinPos();
        }
      }
    };
    Component.prototype._selectUp = function(){
      if(this.curKeyDown === "hour"){
        var preHour = this.hour-1;
        if(this.minInfo.min>=this.maxMin){
          if(preHour<=this.minInfo.hour){
              return;
          }
        }
        else{
          if(preHour<this.minInfo.hour){
              return;
          }
        }
        this.setMinDisabled(preHour);
        if(preHour>=this.hourRange[0]){
          this.hour = preHour;
          this.setValue(this.getValueStr());
          this.setHourPos();
        }
      }else{
        var preMin = this.min-this.minSpan;
        if(this.hour === this.minInfo.hour){
          if(preMin< this.minInfo.min){
            return;
          }
        }
        if(preMin>=0){
          this.min = preMin;
          this.setValue(this.getValueStr());
          this.setMinPos();
        }
      }
    };
    Component.prototype.setMinValue = function(str){
      this.minInfo = this.convertStrToVal(str);
      var curHour;
      if(this.minInfo.hour>=this.hour){
        if(this.minInfo.min>=this.maxMin){
          this.hour = this.minInfo.hour+1;
        }else{
          this.hour = this.minInfo.hour;
        }
        if(this.minInfo.min>=this.min){
          this.min = this.minInfo.min;
        }
        if(this.minInfo.min>=this.maxMin){
          this.min  = 0;
        }
      }
      this.setMinDisabled(this.hour);
      this.setValue(this.getValueStr());
      for(var i=this.hourRange[0];i<=this.hourRange[1];i++){
        var item  = this.hourDomDict[i.toString()] ;
        if(this.minInfo.min>=this.maxMin){
          if(this.minInfo.hour>=i){
            item.addClass("yy-tp-item-disabled");
          }else{
            item.removeClass("yy-tp-item-disabled");
          }
        }else{
          if(this.minInfo.hour>i){
            item.addClass("yy-tp-item-disabled");
          }else{
            item.removeClass("yy-tp-item-disabled");
          }
        }

      }

      this.setHourPos();
      this.setMinPos();
    };

    Component.prototype.initHour = function(){
      this.hourDomDict ={};
      for(var i=this.hourRange[0];i<=this.hourRange[1];i++){
        var hourItem = $("<div data-tp='hour' data-val='"+i+"' class='yy-tp-item'>"+(i<10?"0"+i:i)+" 时</div>");
        this.hourWrapper.append(hourItem);
        this.hourDomDict[i.toString()] = hourItem;
      }
    };
    Component.prototype.initMin = function(){
      this.minDomDict ={};
      var minMin = 0;
      for(var i=0;i<=59;i++){
        if(minMin>59){
          break;
        }
        var minItem = $("<div data-tp='min' data-val='"+minMin+"' class='yy-tp-item'>"+(minMin<10?"0"+minMin:minMin)+" 分</div>");
        this.minWrapper.append(minItem);
        this.minDomDict[minMin.toString()] = minItem;
        this.maxMin = minMin;
        minMin += this.minSpan;

      }
    };

    Component.prototype.convertStrToVal = function(str){
      var str_arr = str.split(":");
      var Re = {hour:this.hourRange[0],min:0};
      if(str_arr.length>=2){
        var hour =str_arr[0];
        var min = str_arr[1];
        if(!isNaN(hour)){
           hour = parseInt(hour);
          if(hour>=this.hourRange[0]&&hour<=this.hourRange[1]){
            Re.hour = (hour);
          }
        }
        if(!isNaN(min)){
          min = parseInt(min);
          if(min>=0&&min<=59){
            Re.min = Math.floor(min/this.minSpan)*this.minSpan;
          }
        }
      }
      return Re;
    },
    Component.prototype.setValue = function(str,isInit){
      var _this = this;
      var vals = this.convertStrToVal(str);
      this.hour = vals.hour;
      this.min = vals.min;

      if(this.selectedHourItem){
        this.selectedHourItem.removeClass("yy-tp-item-selected");
      }
      this.selectedHourItem = this.hourDomDict[this.hour.toString()];
      this.selectedHourItem.addClass("yy-tp-item-selected");


      if(this.selectedMinItem){
        this.selectedMinItem.removeClass("yy-tp-item-selected");
      }
      this.selectedMinItem = this.minDomDict[this.min.toString()];
      this.selectedMinItem.addClass("yy-tp-item-selected");

      var val = this.getValueStr();
      this.input.val(val);


      if(this.changeMethod){
        this.changeMethod.call(this.pageview.plugin,this,{value:val});
      }

    },
    Component.prototype.getValueStr = function(){
      return (this.hour<10?"0"+this.hour:this.hour)+":"+(this.min<10?"0"+this.min:this.min);
    };
    Component.prototype.itemClick = function(e){
      e.stopPropagation();
      e.preventDefault();
      var tp_type = e.target.getAttribute("data-tp");
      var val = e.target.getAttribute("data-val");
      if($(e.target).hasClass("yy-tp-item-disabled")){
        this.input.focus();
        return;
      }

      if(tp_type==="hour"){
        var hour = parseInt(val);
        if(this.minInfo){
          this.setMinDisabled(hour);
        }

        this.hour =hour;
        this.selectedHourItem && this.selectedHourItem.removeClass("yy-tp-item-selected");
        this.selectedHourItem = this.hourDomDict[val];
        this.selectedHourItem.addClass("yy-tp-item-selected");

        this.setHourPos();

      }else if(tp_type==="min"){
        this.min = parseInt(val);
        this.selectedMinItem && this.selectedMinItem.removeClass("yy-tp-item-selected");
        this.selectedMinItem = this.minDomDict[val];
        this.selectedMinItem.addClass("yy-tp-item-selected");

        this.hide();
      }
      var val = this.getValueStr();
      if(this.changeMethod){
        this.changeMethod.call(this.pageview.plugin,this,{value:val});
      }
      this.input.val(val);
      this.input.focus();
    };

    Component.prototype.getValue = function(){

      return this.getValueStr();

    };


    Component.prototype.setMinDisabled = function(hour){
      if(this.minInfo.hour === hour){
        var minMin = 0,temMinMin = -1;
        for(var i=0;i<=59;i++){
          if(minMin>59){
            break;
          }
          var item = this.minDomDict[minMin.toString()];
          if(minMin<this.minInfo.min){
            item.addClass("yy-tp-item-disabled");
          }else{
            if(temMinMin===-1){
              temMinMin = minMin;
            }
            item.removeClass("yy-tp-item-disabled");
          }
          minMin += this.minSpan;
        }
        if(this.min<=this.minInfo.min){
          this.min = temMinMin;
          this.setValue(this.getValueStr());
          this.setMinPos();
        }
      }else{
        for(var key in this.minDomDict){
          this.minDomDict[key].removeClass("yy-tp-item-disabled");
        }
      }
    };


    Component.prototype.hide = function(){
      this.dropdown.css({visibility:"hidden"});
      this.pageview.pageManager.cancelBodyClick(this.id);
    };
    Component.prototype.setHourPos = function(){
      var hourpos = this.selectedHourItem.position();
      var st = this.hourWrapper.scrollTop();
      var pos = hourpos.top+st;
      pos -= 56;

      this.hourWrapper.scrollTop(pos);
    };
    Component.prototype.setMinPos = function(){
      var minpos = this.selectedMinItem.position();

      var st = this.minWrapper.scrollTop();
      var pos = minpos.top+st;
      pos -= 56;


      this.minWrapper.scrollTop(pos);
    };
    Component.prototype.show = function(e){
      var _this = this;
      this.curKeyDown = "hour";
      var pos =this.$el.offset();
      var h = this.$el.height();
      this.dropdown.css({top:(pos.top+h)+"px",left:pos.left+"px","visibility":"visible"});
      this.pageview.pageManager.regeistBodyClick(this.id,function(){
        _this.hide();
      });
      this.setValue(this.getValueStr());

      this.setMinPos();
      this.setHourPos();


    },
    Component.prototype._init=function(){
      var _this = this;
      this.dropdown = $("<div class='yy-tp-dropdown'></div>");
      var hourOutWrapper =  $("<div class='yy-tp-hour'></div>");
      this.hourWrapper = $("<div class='yy-tp-hour-inner'></div>");
      hourOutWrapper.append(this.hourWrapper);
      var minoutWrapper = $("<div class='yy-tp-min'></div>");

      this.minWrapper = $("<div class='yy-tp-min-inner'></div>");

      minoutWrapper.append(this.minWrapper);
      this.dropdown.append(hourOutWrapper).append(minoutWrapper);
      this.initHour();
      this.initMin();
      this.pageview.$el.append(this.dropdown);
      this.dropdown.bind("click",function(e){
        _this.itemClick(e);
      });
      this.setValue(this.config.value||"",true);
    };


    return Component;
});
